<template>
    <view class="content login-page">
        <view class="u-m-l-40 u-p-t-80">
            <view class="u-font-60">您好，</view>
            <view class="u-font-30" style="color:#9DA1AF;">{{ loginTitleTxt }}</view>
        </view>
        <u-tabs
            :list="list"
            barWidth="150"
            barHeight="5"
            height="100"
            style="margin:30rpx 0 20rpx 0;"
            active-color="#AB61FF"
            :is-scroll="false"
            :current="current"
            @change="change"
        ></u-tabs>
        <view class="form">
            <block v-if="current">
                <view class="formInput">
                    <view class="codeview">
                        <image src="../../static/register/yhm.png" style="width: 48rpx;height:48rpx;margin-right:20rpx;" mode="aspectFill"></image>
                        <u-input
                            type="text"
                            class="input"
                            :clearable="clearable"
                            id="name"
                            v-model="params.name"
                            placeholder="请输入您的账号"
                            @blur="getLoginName"
                            :maxLength="18"
                        ></u-input>
                    </view>
                </view>
                <view class="formInput">
                    <view class="codeview">
                        <image src="../../static/register/mm.png" style="width: 48rpx;height:48rpx;margin-right:20rpx;" mode="aspectFill"></image>
                        <u-input type="password" class="input" :clearable="clearable" id="ddcode" v-model="params.password" placeholder="请输入密码" :maxLength="4"></u-input>
                    </view>
                </view>
                <view class="u-flex u-row-between u-p-20 yellow">
                    <view>
                        新用户
                        <text @click="register">注册</text>
                    </view>
                    <text @click="forget">忘记密码</text>
                </view>
            </block>
            <block v-else>
                <view class="formInput">
                    <view class="codeview" style="width:60%;">
                        <image src="../../static/register/mb.png" style="width: 48rpx;height:48rpx;margin-right:20rpx;" mode="aspectFill"></image>
                        <u-input
                            type="text"
                            class="input"
                            :clearable="clearable"
                            id="name"
                            v-model="params.phone"
                            placeholder="请输入您的手机号"
                            @blur="getLoginName"
                            :maxLength="18"
                        ></u-input>
                    </view>
                </view>
                <view class="formInput">
                    <view class="codeview" style="width:60%;">
                        <image src="../../static/register/code.png" style="width: 48rpx;height:48rpx;margin-right:20rpx;" mode="aspectFill"></image>
                        <u-input type="number" class="input" :clearable="clearable" id="ddcode" v-model="params.code" placeholder="请输入短信验证码" :maxLength="4"></u-input>
                    </view>
                    <view class="send" id="sendCode">
                        <button size="mini" :disabled="btnDis" @tap="sendCode">{{ btnText }}</button>
                    </view>
                </view>
            </block>
        </view>
        <view class="btn-row"><button @tap="debunceLogin" :loading="submitBtnDis" :disabled="submitBtnDis || submitBtnDisKey">登录</button></view>

        <view class="xieyi">
            <view class="xy xieyi-text">
                <u-checkbox active-color="#AB61FF" @change="checkboxChange" v-model="isAggre"></u-checkbox>
                <view>
                    已阅读且同意
                    <text class="xieyi-fwxy" @click="toAgreement('3')">《服务协议》</text>
                    和
                    <text class="xieyi-fwxy" @click="toAgreement('4')">《隐私政策》</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { mapState, mapMutations, mapGetters, mapActions } from 'vuex';
import mInput from '@/components/m-input/m-input.vue';
import graceChecker from '@/common/graceChecker.js';
import formRuleConfig from '@/config/formRule.config.js';

export default {
    components: {
        mInput
    },
    data() {
        return {
            list: [
                {
                    name: '手机号'
                },
                {
                    name: '账号密码'
                }
            ],
            current: 0,
            clearable: true,
            placeholderColor: '#f00',
            loginTitleTxt: this.$mConfig.loginTitleTxt,
            copyrightTxt: this.$mConfig.copyrightTxt,
            btnDis: false,
            submitBtnDis: false,
            btnText: '获取验证码',
            params: {
                name: '',
                password: ''
            },
            isAggre: false, //是否同意协议
            reqBody: {},
            // 如果为登录状态 默认跳转的地址
            redirectRoute: this.$mRoutesConfig.main,
            routeQuery: {},
            latitude: '',
            longitude: '',
            providerList: [],
            positionTop: 0,
            hasProvider: true,
            openid: '',
            userinfo: []
        };
    },
    onLoad(query) {
        if (query.type && query.type == 'msg') {
            //定位微信位置
            this.initPosition(query.type);
        }
        if (query.data) {
            let result = JSON.parse(decodeURIComponent(query.data));
            this.openid = result.openid;
            this.userinfo = result.userinfo;
        }
        // #ifdef APP-PLUS
        uni.hideTabBar();
        // #endif
    },
    onShow() {
        this.initPosition();
    },
    onBackPress(options) {
        if (options.from === 'navigateBack') {
            return false;
        }
        this.back();
        return true;
    },
    //导航按钮
    onNavigationBarButtonTap(obj) {
        this.register();
    },
    computed: {
        //...mapState(['openId']),
        ...mapGetters(['hasLogin']),

        submitBtnDisKey() {
            if (this.current) {
                let checkParams = {};
                //checkParams['openId'] = this.$mConfig.testOpenId;
                checkParams['name'] = this.params.name;
                checkParams['name'] = this.params.name;
                checkParams['password'] = this.params.password;
                let res = graceChecker.check(checkParams, formRuleConfig.loginRule);
                return !res;
            }
        }
    },
    onReady() {},
    methods: {
        forget() {
            this.$mRouter.push({
                route: this.$mRoutesConfig.forget
            });
        },
        checkboxChange(e) {
            this.isAggre = e.value;
        },
        change(e) {
            console.log('current', e);
            this.current = e;
        },
        getLoginName(e) {
            // #ifdef APP-PLUS
            console.log(e);
            var val = e.detail.value;
            this.params.name = val;
            // #endif
        },
        back() {
            uni.navigateBack({
                delta: 2
            });
        },
        clearPassword() {
            this.params.password = '';
        },
        clearName() {
            this.params.name = '';
        },
        blue_input() {
            uni.hideKeyboard();
        },
        register() {
            this.$mRouter.push({
                route: this.$mRoutesConfig.register
            });
        },
        initPosition(flag) {
            /**
             * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
             * 反向使用 top 进行定位，可以避免此问题。
             */
            if (flag) {
                this.positionTop = uni.getSystemInfoSync().windowHeight - 60;
            } else {
                this.positionTop = uni.getSystemInfoSync().windowHeight - 80;
            }
        },
        debunce(func, wait) {
            let time;
            return function() {
                clearTimeout(time);
                time = setTimeout(func, wait);
            };
        },
        async debunceLogin() {
            if (!this.isAggre) {
                uni.showToast({
                    title: '请先阅读并勾选《服务协议》和《隐私政策》',
                    icon: 'none'
                });

                return;
            }
            this.debunce(this.bindLogin(), 1000);
        },
        // 登录
        async bindLogin() {
            uni.showLoading({
                title: '',
                mask: true
            });
            // debugger;
            try {
                if (this.current) {
                    this.reqBody['name'] = this.$u.trim(this.params['name'], 'all');
                    this.reqBody['password'] = this.$u.trim(this.params['password'], 'all');
                } else {
                    this.reqBody['phone'] = this.params['phone'];
                    this.reqBody['code'] = this.params['code'];
                }
                // #ifdef APP-PLUS
                this.reqBody['clientId'] = plus.push.getClientInfo().clientid;
                this.reqBody['systemInfo'] = plus.os.name.toLowerCase() === 'android' ? '2' : '1';
                // #endif
                // let checkRes = graceChecker.check(this.reqBody, formRuleConfig.loginRule);
                // if (!checkRes) {
                // 	uni.showToast({
                // 		title: graceChecker.error,
                // 		icon: 'none'
                // 	});
                // 	return;
                // }

                // // 校验通过...
                // this.submitBtnDis = true;
                setTimeout(function() {
                    this.submitBtnDis = false;
                }, 2000);

          

                let data = {};
                if (this.current) {
                    data = await this.$apis.login(this.reqBody);
                } else {
                    data = await this.$apis.smsLogin(this.reqBody);
                }
                setTimeout(function() {
                    uni.hideLoading();
                }, 2000);
                if (data.code == 200) {
                    // 前端自动登录
                    this.$store.commit('SET_USERINFO', data.data);
                    uni.setStorageSync('userInfo', data.data);
                    uni.showToast({
                        title: '登录成功',
                        icon: 'none'
                    });
                    // this.$store.commit('WEBSOCKET_SEND', JSON.stringify({
                    // 	type: 'login',
                    // 	msg: {
                    // 		userId: data.data.id,
                    // 		name: data.data.name
                    // 	}
                    // })); //发送当前聊天窗口信息

                    var that = this;

                    that.$mRouter.switchTab({
                        route: that.$mRoutesConfig.index,
                        success() {
                            console.log('success');
                        },
                        fail(err) {
                            console.log('跳转失败', err);
                        }
                    });
                } else {
                    uni.showToast({
                        title: data.message,
                        icon: 'none'
                    });
                    this.submitBtnDis = false;
                    return;
                }
            } catch (e) {
                console.log(e);
                this.submitBtnDis = false;

                setTimeout(function() {
                    uni.hideLoading();
                }, 2000);
            }
        },

        // 发送验证码
        async sendCode() {
            console.log('send');

            if (!this.params.phone) {
                uni.showToast({
                    title: '请输入手机号',
                    icon: 'none'
                });
                return;
            }
            if (!/^1[23456789]\d{9}$/.test(this.params.phone)) {
                uni.showToast({
                    title: '请填写正确的手机号',
                    icon: 'none'
                });
                return;
            }
            //#ifdef APP-PLUS
            let clientId = plus.push.getClientInfo().clientid;
            //#endif

            //发送验证码

            await this.$apis.getSmsCode({
                phone: this.params.phone
            });

            // uni.showToast({
            // 	title: '发送成功'
            // });
            // 开启倒计时
            this.countDown();
        },

        // 验证码倒计时
        countDown() {
            let t = null;
            let timer = 60;
            this.btnDis = true;
            clearInterval(t);
            this.btnText = `${timer}s`;
            t = setInterval(() => {
                if (timer == 0) {
                    clearInterval(t);
                    this.btnText = '重新发送';
                    this.btnDis = false;
                    return;
                }
                timer--;
                this.btnText = `${timer}s`;
            }, 1000);
        },
        async bindHome() {
            uni.switchTab({
                url: '/pages/main/main'
            });
        },
        toAgreement(type) {
            uni.navigateTo({
                url: '/pages/login/agreement?type=' + type
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.orange {
    color: rgb(250, 133, 0);
}
.yellow {
    color: #ab61ff;
}
#sendCode {
    align-items: flex-end;
    font-size: 30rpx;
}

.icon {
    font-family: iconfont !important;
    font-style: normal;
    color: #000000;

    &.isSelect {
        &:before {
            content: '\e64b';
            color: #fa8500;
            font-size: 32rpx;
            margin-right: 20rpx;
        }
    }

    &.selected {
        &:before {
            content: '\e649';
            color: rgb(250, 133, 0);
            font-size: 32rpx;
            margin-right: 20rpx;
        }
    }
}

.action-row {
    display: flex;
    flex-direction: row;
    justify-content: center;
    padding-bottom: 100rpx;

    view {
        font-size: 30rpx;
        color: #2a9f93;
    }
}

.form {
    padding: 65rpx 40rpx 90rpx 40rpx;
    box-sizing: border-box;

    .formInput {
        background: rgba(255, 255, 255, 1);
        border-bottom: 1px solid #dadeed;
        height: 88rpx;
        line-height: 88rpx;
        margin-bottom: 40rpx;
        padding-bottom: 35rpx;
        color: #000;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: space-between;

        .codeview {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .input {
                padding: 0 30rpx;
                font-size: $uni-font-size-base;
            }

            image {
                width: 48rpx;
                height: 48rpx;
            }
        }

        .send {
            height: 100%;
            border-radius: 0 4rpx 4rpx 0rpx;
            font-size: 28rpx;
            display: flex;
            align-items: center;
            flex: 0 0 256rpx;
            justify-content: center;
        }

        .button {
            height: 100%;
            width: 100%;
            color: #fff;
        }
    }

    .menus {
        margin-top: 17rpx;
        display: flex;
        font-size: 28rpx;
        justify-content: space-between;
    }

    .xieyi {
        width: 100%;

        margin-top: 30rpx;

        .xieyi-text {
            font-size: 24rpx;
            color: #cccccc;
            display: flex;
            justify-content: left;
            align-items: center;
        }

        .xieyi-fwxy {
            font-family: PingFang-SC-Medium;
            font-size: 24rpx;
            font-weight: normal;

            color: #2a9f93;
            display: flex;
            justify-content: left;
        }
    }
}

.bottom {
    height: 50rpx;
    display: flex;
    flex-wrap: nowrap;
    justify-content: left;
    align-items: center;
    padding: 0 31px 0px 31px;
    font-family: PingFang-SC-Medium;
    font-size: 24rpx;
    font-weight: normal;
    font-stretch: normal;
    letter-spacing: 0px;
    color: #cccccc;
    margin-bottom: 20rpx;
    justify-content: center;

    .xieyi {
        font-family: PingFang-SC-Medium;
        font-size: 24rpx;
        font-weight: normal;
        letter-spacing: 0px;
        color: #2a9f93;
    }
}

.btn-row {
    padding: 0 57rpx 30rpx 57rpx;
}

.logo {
    margin: 77rpx 0;
    width: 139rpx;
    height: 139rpx;
    border-radius: 14rpx;
}

.action-row navigator {
    color: #007aff;
    padding: 0 20rpx;
}

.login-page {
    position: relative;
}

.input-group {
    background-color: #fff;
    // border-radius: 10rpx;
    margin-top: 10rpx;
}

.tips {
    padding-left: 20rpx;
    margin-top: 20rpx;
    color: #8c8c8c;
    font-size: 26rpx;
}

.vs {
    position: absolute;
    bottom: 70rpx;
    text-align: center;
    width: 100%;
}

button,
button[type='primary'] {
    background: #ab61ff;
    border-radius: 40rpx;
    color: #fff;
    border: 0;
    z-index: 20;
}
button[disabled][type='primary'],
button[disabled] {
    color: #fff;
    background: #ab61ff;
    border-radius: 40rpx;
}

.xy {
    display: flex;
    justify-content: center;
    padding-bottom: 60rpx;
    text-align: center;
    color: #c4c7cc;
}

.xy text {
    color: #fa8500;
}

.sendCode {
    display: flex;
    align-items: right;
    flex-direction: row-reverse;
    box-sizing: border-box;
    align-items: stretch;

    //width:230rpx;
    button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 230rpx;
        height: 52rpx;
        line-height: 52rpx;
        background-color: #fa8500;
        border-radius: 26rpx;
        color: #fff;
        font-size: 26rpx;

        &::after {
            display: none;
        }
    }
}

.oauth-row {
    display: flex;
    flex-direction: row;
    justify-content: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
}

.oauth-image {
    width: 60rpx;
    height: 60rpx;
    padding: 20rpx;
    border: 1rpx solid #f5f5f5;
    border-radius: 100rpx;
    margin: 0 auto;
    background-color: #ffffff;
}

.oauth-image image {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
}

.u-font-60 {
    font-size: 60rpx;
}
</style>
